<!DOCTYPE html>
<script src="../../resources/run-after-layout-and-paint.js"></script>
<script>
if (window.testRunner) {
  testRunner.dumpAsText();
  window.onload = function() {
    runAfterLayoutAndPaint(mutateTree, true);
  };
}
const svgNs = 'http://www.w3.org/2000/svg';
function buildPattern(patternId, refId) {
  var pattern = document.createElementNS(svgNs, 'pattern');
  var rect = pattern.appendChild(document.createElementNS(svgNs, 'rect'));
  pattern.setAttribute('id', patternId);
  pattern.setAttribute('width', 1);
  pattern.setAttribute('height', 1);
  rect.setAttribute('width', 100);
  rect.setAttribute('height', 100);
  rect.setAttribute('fill', 'url(#' + refId + ')');
  return pattern;
}
function mutateTree() {
  // Get reference to rect in pattern#p2 before inserting the pattern.
  var p2rect = document.getElementsByTagName('rect')[1];

  // Add a pattern#p3 and a reference to it from pattern#p2 to form a cycle.
  var defs = document.querySelector('defs');
  defs.appendChild(buildPattern('p3', 'p1'));
  p2rect.setAttribute('fill', 'url(#p3)');
}
</script>
<p>PASS if no crash (stack overflow).</p>
<svg width="100" height="100">
  <rect width="100" height="100" fill="url(#p1)"/>
  <defs>
    <pattern id="p2" width="1" height="1">
      <rect width="100" height="100"/>
    </pattern>
    <pattern id="p1" width="1" height="1">
      <rect fill="url(#p2)" width="100" height="100"/>
    </pattern>
  </defs>
</svg>
